//import logo from './logo.svg';
import React from 'react';
import { Table, Input, Popconfirm, message, Popover } from 'antd';
import 'antd/dist/antd.css';
import './App.css';

function cancel(e) {
  console.log(e);
  message.error('删除失败！');
}
const EditableCell = ({ editable, value, onChange, ID, setWorkShow }) => (
  <div href={ID} key={ID} className="flexRow" onMouseOver={(e) => !editable ? setWorkShow(ID) : {}}>
    {editable
      ? <Input style={{ margin: '-5px 0' }} value={value} onChange={e => onChange(e.target.value)} />
      : value
    }
  </div>
);

class NavigationBar extends React.Component {
  render() {
    return (
      <div>

      </div>
    )
  }
}
class AppHead extends React.Component {
  render() {
    return (
      <div className={this.props.PopupVisible ? 'AppHead flexRow blur' : 'AppHead flexRow'}>
        <NavigationBar />
        <div className="flexRow">
          <img src="https://z3.ax1x.com/2021/05/30/2ELDTU.png" alt="logo" width="60" style={{ marginLeft: '3rem' }}></img>
          <span style={{ marginLeft: '1rem', fontSize: '2rem', color: '#ebdbc5', fontWeight: '700', textShadow: '0px 0px 0.6px 0.2px #66666620', fontFamily: 'Fina' }}>FINA</span>
        </div>
      </div>
    )
  }
}
class ContextMenu extends React.Component {
  state = {
    visible: false,
  };

  componentDidMount() {
    document.addEventListener('contextmenu', this.__handleContextMenu__);
    document.addEventListener('click', this.__handleClick__);
    document.addEventListener('scroll', this.__handleClick__);
  };

  componentWillUnmount() {
    document.removeEventListener('contextmenu', this.__handleContextMenu__);
    document.removeEventListener('click', this.__handleClick__);
    document.removeEventListener('scroll', this.__handleClick__);
  }

  __handleContextMenu__ = (event) => {
    event.preventDefault();

    this.setState({ visible: true });

    let { clientX } = event;
    let { clientY } = event;
    //点击的位置
    let { innerHeight } = window;
    let { innerWidth } = window;
    //窗口长宽
    let { offsetHeight } = this.root;
    let { offsetWidth } = this.root;
    //菜单的边缘
    let right = (clientX + offsetWidth) > innerWidth;
    //右超界
    let bottom = (clientY + offsetHeight) > innerHeight;
    //下超界

    // console.log('right',right );
    // console.log('bottom',bottom );
    if (right) {
      this.root.style.left = `${clientX - offsetWidth - 5}px`;
    } else {
      this.root.style.left = `${clientX + 5}px`;
    }

    if (bottom) {
      this.root.style.top = `${clientY - offsetHeight - 5}px`;
    } else {
      this.root.style.top = `${clientY + 5}px`;
    }
  };

  __handleClick__ = (event) => {
    console.log('eventClick', event)
    //鼠标单击事件，如点击位置在菜单外，且菜单没有被显示
    let { visible } = this.state;
    let wasOutside = !(event.target.contains === this.root);
    if (wasOutside && visible) this.setState({ visible: false, });
  };

  __handleClick__ = () => {
    let { visible } = this.state;

    if (visible) this.setState({ visible: false });
  };

  render() {
    let { visible } = this.state;
    return (visible || null) &&
      <div ref={ref => { this.root = ref }} className="contextMenu">
        <div className="contextMenuOption" onClick={() => this.props.addNewRow()}>新建行</div>
        <div className="contextMenuOption" onClick={(e) => this.props.showPopUp(e, true)}>新建工作表</div>
        <div className="contextMenuOption" onClick={() => this.props.openCloseListen(true)}>设置</div>
        <div className="contextMenuSeparator" />
        <div className="contextMenuOptionEnabled">关于FINA</div>
      </div>
  };
}
class SmallWatch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showDel: false
    }
    this.setHover = this.setHover.bind(this);
  }
  setHover(e) {
    if (this.props.data_key === 0) {
      return;
    }
    this.setState({
      showDel: e
    })
  }
  render() {
    return <div className="SmallWatch flexRow" style={{ backgroundColor: (this.props.data_key === this.props.choose) ? '#ffffff' : '' }}
      onClick={(e) => this.props.changeChoose(e, this.props.data_key)} onMouseOver={() => this.setHover(true)}
      onMouseOut={() => this.setHover(false)}>
      {this.props.name}
      <Popconfirm title="确认删除该表单？" onConfirm={(e) => this.props.delWatchItem(e, this.props.data_key)} onCancel={cancel} okText="是" cancelText="否">
        <div className="flexCenter delWatch" style={{ opacity: (this.state.showDel) ? '1' : '0' }}>
          <img src="https://z3.ax1x.com/2021/05/28/2iy0MV.png" alt="×" border="0" width="8"></img>
        </div>
      </Popconfirm>
    </div>
  }
}
class WatchList extends React.Component {
  constructor(props) {
    super(props);
    console.log('chooseItem', this.props.chooseItem)
  }
  render() {
    return (
      <div className="leftApp">
        {
          this.props.data.map((data, item) => {
            return <SmallWatch name={data.name} key={item} choose={this.props.chooseItem} changeChoose={this.props.changeChoose} data_key={item}
              delWatchItem={this.props.delWatchItem}></SmallWatch>
          })
        }
        <div className="addWatchListItem flexCenter" onClick={(e) => this.props.showPopUp(e, true)}>+</div>
      </div>
    )
  }
}
class SearchBar extends React.Component {
  state = {
    value: ""
  }
  onKeyUp(e) {
    if (e.key === "Enter") {
      document.getElementById("searchInput").blur()
    }
  }
  ReSet() {
    this.setState({ value: '' });
    let params = {}
    params.target = {}
    params.target.value = ''
    this.props.searchOnBlur(params)
  }
  render() {
    return (
      <div className="searchBar flexRow">
        <img src="https://z3.ax1x.com/2021/05/29/2k74IA.png" alt="search" border="0" width="16"></img>
        <input placeholder="模糊搜索" onBlur={(e) => this.props.searchOnBlur(e)} id="searchInput"
          onKeyUp={this.onKeyUp.bind(this)}
          onFocus={(e) => this.setState({ value: "" })} value={this.state.value}
          onChange={(e) => this.setState({ value: e.target.value })}></input>
        <div className="flexCenter">
          <img src="https://z3.ax1x.com/2021/05/29/2kxk5D.png" alt="重置搜索" width="18" border="0"
            style={{ cursor: 'pointer', transition: 'all ease 1s' }} onClick={() => this.ReSet()}></img>
        </div>
      </div>
    );
  }
}
class WorkToolBar extends React.Component {
  render() {
    return (
      <div className="WorkToolBar flexRow">
        <SearchBar searchOnBlur={this.props.searchOnBlur}></SearchBar>
      </div>
    )
  }
}
class WorkControl extends React.Component {
  constructor(props) {
    super(props)
    this.modelToFind = {
      'money': 'money',
      'moneyin': 'money',
      'moneyout': 'money'
    }
    this.model = {
      money: {
        render: (e) => {
          if (e.length === 0) {
            return (<div className="WorkControl flexCenter" style={{ color: '#999999', fontWeight: '700', fontSize: '1.2rem' }}>NONE</div>)
          }
          let account = e.reduce((prev, cur) => {
            if (typeof prev === "string") {
              prev = parseInt(prev)
            }
            return prev + parseInt(cur)
          })
          let positive = e.reduce((prev, cur) => {
            if (typeof prev === "string") {
              prev = parseInt(prev)
            }
            cur = parseInt(cur);
            if (cur > 0) {
              return prev + cur;
            } else {
              return prev;
            }
          })
          return (
            <div className="flexRow WorkShow" style={{ justifyContent: 'space-evenly', fontWeight: '700', fontSize: '1.25rem', color: '#333333' }}>
              <div style={{ color: 'rgb(238,200,48)' }} className="flexRow"><img src="https://z3.ax1x.com/2021/05/29/2AyJhQ.png" width="18" border="0" alt="余额"></img><span href="money">{account}</span></div>
              <div style={{ color: 'rgb(54,171,96)' }} className="flexRow"><img src="https://z3.ax1x.com/2021/05/29/2AsPIg.png" width="18" border="0" alt="收入"></img><span href="money">{positive}</span></div>
              <div style={{ color: 'rgb(229,64,52)' }} className="flexRow"><img src="https://z3.ax1x.com/2021/05/29/2AyN1s.png" width="18" border="0" alt="支出"></img><span href="money">{account - positive}</span></div>
            </div>
          )
        }
      }
    }
  }
  render() {
    let filterWord = this.props.workShow;
    if (!filterWord || filterWord === "" || filterWord === "action") {
      return (
        <div className="WorkControl flexCenter" style={{ color: '#999999', fontWeight: '700', fontSize: '1.2rem' }}>未选择</div>
      )
    }
    let ControlItem = []
    for (const iterator of this.props.dataSource) {
      if (iterator[filterWord]) {
        ControlItem.push(iterator[filterWord])
      }
    }
    let model = this.modelToFind[filterWord]
    if (model) {
      let demo = this.model[model].render(ControlItem)
      return (
        <div className="WorkControl flexCenter">
          {demo}
        </div>
      )
    }
    return (
      <div className="WorkControl flexCenter" style={{ color: '#999999', fontWeight: '700', fontSize: '1.2rem' }}>{filterWord}</div>
    )
  }
}
class WorkArea extends React.Component {
  render() {
    return (
      <div className="WorkArea">
        <Table
          key={this.props.watchListChooseIndex}
          columns={this.props.columns} dataSource={this.props.dataSource} rowSelection={this.props.rowSelection} scroll={{ x: 1200, y: 360 }}>

        </Table>
        <div className="addData" style={{ top: (this.props.dataSource.length === 0 ? '0px' : '-4rem') }}>
          <div className="flexRow">
            <div className="addControl flexCenter" onClick={this.props.addNewRow} style={{width:'2rem'}}><a href="#addNewRow">+</a></div>
            <Popconfirm title="确认删除这些数据？" onConfirm={this.props.delLotsOfRow} onCancel={cancel} okText="是" cancelText="否">
              <div className="addControl flexCenter" style={{  width: '4rem',marginLeft:'1rem'}}><a href="#delRows">删除</a></div>
            </Popconfirm>
          </div>
        </div>
      </div>
    )
  }
}
class WorkSpace extends React.Component {
  render() {
    return (
      <div className="rightApp">
        <WorkToolBar searchOnBlur={this.props.searchOnBlur}></WorkToolBar>
        <WorkArea columns={this.props.columns} dataSource={this.props.dataSource} rowSelection={this.props.rowSelection}
        delLotsOfRow={this.props.delLotsOfRow}
        addNewRow={this.props.addNewRow}></WorkArea>
        <WorkControl dataSource={this.props.dataSource} workShow={this.props.workShow}></WorkControl>
      </div>
    )
  }
}
class MakeWatchItem extends React.Component {
  loadTable(e) {
    this.setState({
      chooseItem: e
    })
  }
  handleChangeInputVal(e) {
    let { value } = e.target;
    this.setState({
      val: value
    })
  }
  state = {
    columns: [],
    chooseItem: 0,
    visible: false,
    val: ''
  }
  handleVisibleChange() {
    this.setState({
      visible: !this.state.visible
    })
  }
  render() {
    console.log('sm', this.props.MODEL[this.state.chooseItem])
    return (
      <div className="flexColumn" onClick={(e) => { e.stopPropagation() }}
        style={{ width: '80vw', height: '40vh', backgroundColor: '#f1f1f1', position: 'relative', borderRadius: '9px', boxShadow: ' 0px 0px 18px 3px rgba(80,80,80,.8)', overflow: 'hidden' }}>
        <div style={{ fontSize: '14px', margin: '0.5rem 1rem 0.5rem 1rem', width: '100%', position: 'relative', fontWeight: '700' }}>可选模板</div>
        <div className="flexRow" style={{ width: '100%', maxHeight: '12vh', flexWrap: 'wrap' }}>
          {
            this.props.MODEL.map((item, index) => {
              return (
                <Popover key={index} style={{ zIndex: '999999' }} content=
                  {
                    <div className="flexRow popupForm">
                      <input placeholder="请输入表名" value={this.state.val} onChange={this.handleChangeInputVal.bind(this)}></input>
                      <button onClick={(e) => this.props.addNewWatchItem(this.state.val, this.state.chooseItem)}>确认</button>
                    </div>
                  }
                  title="表格名"
                  trigger="click"
                  visible={this.state.chooseItem === index && this.state.visible}
                  onVisibleChange={this.handleVisibleChange.bind(this)}
                >
                  <div className="flexCenter PopWatch" onMouseOver={() => this.loadTable(index)}>{item.modelData.modelName}</div>
                </Popover>
              )
            })
          }
        </div>
        <Table style={{ position: 'absolute', bottom: '0' }} columns={this.props.MODEL[this.state.chooseItem].modelData.columns} dataSource={[]} scroll={{ x: '70vw', y: '20vh' }}></Table>
      </div>
    )
  }
  componentWillUpdate(e) {
    // console.log('Update',e )
  }
}
class Popup extends React.Component {
  render() {
    return (
      this.props.visible ?
        <div className="Popup" onClick={(e) => { this.props.Close(e, false) }}>
          <MakeWatchItem MODEL={this.props.MODEL} addNewWatchItem={this.props.addNewWatchItem}></MakeWatchItem>
        </div> :
        <div></div>
    )
  }
}
class Listen extends React.Component {
  render() {
    if (this.props.listenVisible) {
      return (
        <div style={
          {
            backgroundColor: '#ffffff25',
            width: '100vw', height: '100vh', position: 'absolute', top: '0', left: '0', zIndex: '9999',
            fontSize: '5rem', color: '#00000036'
          }
        } onClick={() => this.props.openCloseListen(false)} className="flexCenter">
          <div style={{ position: 'absolute', top: '2rem', left: '2rem', fontSize: '1rem', color: '#000000', fontWeight: '900' }}>当前正在设置新建行的快捷键。Crtl是固定的，另一个按键可以通过单击键盘上按钮设置。当你确定了设置，单击鼠标结束设置</div>
          Crtl + {this.props.listenKey}
        </div>
      )
    } else {
      return <div></div>
    }
  }
}

class App extends React.Component {
  cacheData = [];
  MODEL = [{
    modelData: {
      modelName: '基础财务模板',
      columns: [{
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        width: 240,
        render: (text, record) => this.renderColumns(text, record, 'time', this.state.watchListChooseIndex),
      },
      {
        title: '事件',
        dataIndex: 'event',
        key: 'event',
        width: 420,
        render: (text, record) => this.renderColumns(text, record, 'event', this.state.watchListChooseIndex),
      },
      {
        title: '金额',
        dataIndex: 'money',
        key: 'money',
        width: 180,
        render: (text, record) => this.renderColumns(text, record, 'money', this.state.watchListChooseIndex),
      },
      {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 120,
        render: (text, record) => {
          const { editable } = record;
          return (
            <div className="editable-row-operations">
              {
                editable ?
                  <span>
                    <a onClick={() => this.save(record.key)} href="#">保存</a>
                    <Popconfirm title="确认删除？" onConfirm={() => this.cancel(record.key)} okText="是" cancelText="否">
                      <a href="#">删除</a>
                    </Popconfirm>
                  </span>
                  : <a onClick={() => this.edit(record.key)} href="#">编辑</a>
              }
            </div>
          );
        },
      }],
      data: {
        key: '',
        time: '',
        event: '',
        money: ''
      },
      modelIndex: 0
    },
  }, {
    modelData: {
      modelName: '财务年报表模板',
      columns: [{
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        width: 180,
        render: (text, record) => this.renderColumns(text, record, 'time', this.state.watchListChooseIndex),
      },
      {
        title: '摘要',
        dataIndex: 'event',
        key: 'event',
        width: 360,
        render: (text, record) => this.renderColumns(text, record, 'event', this.state.watchListChooseIndex),
      },
      {
        title: '收入',
        dataIndex: 'moneyin',
        key: 'moneyin',
        width: 180,
        render: (text, record) => this.renderColumns(text, record, 'moneyin', this.state.watchListChooseIndex),
      },
      {
        title: '支出',
        dataIndex: 'moneyout',
        key: 'moneyout',
        width: 180,
        render: (text, record) => this.renderColumns(text, record, 'moneyout', this.state.watchListChooseIndex),
      },
      {
        title: '经费来源',
        dataIndex: 'source',
        key: 'source',
        width: 200,
        render: (text, record) => this.renderColumns(text, record, 'source', this.state.watchListChooseIndex),
      },
      {
        title: '结余',
        dataIndex: 'money',
        key: 'money',
        width: 180,
        render: (text, record) => this.renderColumns(text, record, 'money', this.state.watchListChooseIndex),
      },
      {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 120,
        render: (text, record) => {
          const { editable } = record;
          return (
            <div className="editable-row-operations">
              {
                editable ?
                  <span>
                    <a onClick={() => this.save(record.key)} href="#">保存</a>
                    <Popconfirm title="确认删除？" onConfirm={() => this.cancel(record.key)} okText="是" cancelText="否">
                      <a href="#">删除</a>
                    </Popconfirm>
                  </span>
                  : <a onClick={() => this.edit(record.key)} href="#">编辑</a>
              }
            </div>
          );
        },
      }],
      data: {
        key: '',
        time: '',
        event: '',
        money: '',
        moneyin: '',
        moneyout: ''
      },
      modelIndex: 1
    },
  }
  ]
  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      this.state.__tempChooseRow__=selectedRows;
    },
    getCheckboxProps: record => ({
      disabled: record.name === 'Disabled User',
    }),
  }
  componentDidUpdate(prevProps, prevState) {
    if (prevState.watchListChooseIndex !== this.state.watchListChooseIndex) {
      let newWatchList = [...this.state.watchList]
      let dataSource = [...this.state.dataSource]
      newWatchList[prevState.watchListChooseIndex].data.dataSource = dataSource
      //存原值

      this.setState({
        columns: newWatchList[this.state.watchListChooseIndex].data.columns,
        dataSource: newWatchList[this.state.watchListChooseIndex].data.dataSource,
        watchList: newWatchList
      })

    }
  }
  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyDown.bind(this));
  }
  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyDown.bind(this));
  }
  handleKeyDown(e) {
    if (this.state.listenVisible) {
      this.setState({
        listenKey: e.key
      })
    } else {
      if (e.ctrlKey && e.key === this.state.listenKey) {
        this.addNewRow();
      }
    }
  }
  constructor(props) {
    super(props);
    this.state = {
      columns: [{
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        width: 240,
        render: (text, record) => this.renderColumns(text, record, 'time', this.state.watchListChooseIndex),
      },
      {
        title: '事件',
        dataIndex: 'event',
        key: 'event',
        width: 420,
        render: (text, record) => this.renderColumns(text, record, 'event', this.state.watchListChooseIndex),
      },
      {
        title: '金额',
        dataIndex: 'money',
        key: 'money',
        width: 180,
        render: (text, record) => this.renderColumns(text, record, 'money', this.state.watchListChooseIndex),
      },
      {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 120,
        render: (text, record) => {
          const { editable } = record;
          return (
            <div className="editable-row-operations">
              {
                editable ?
                  <span>
                    <a onClick={() => this.save(record.key)} href="#">保存</a>
                    <Popconfirm title="确认删除？" onConfirm={() => this.cancel(record.key)} okText="是" cancelText="否">
                      <a href="#">删除</a>
                    </Popconfirm>
                  </span>
                  : <a onClick={() => this.edit(record.key)} href="#">编辑</a>
              }
            </div>
          );
        },
      }],
      dataSource: [],
      rowSelection: this.rowSelection,
      watchList: [
        {
          name: '默认',
          id: '0',
          modelIndex: 0,
          data: {
            columns: [{
              title: '时间',
              dataIndex: 'time',
              key: 'time',
              width: 240,
              render: (text, record, index) => this.renderColumns(text, record, 'time', this.state.watchListChooseIndex),
            },
            {
              title: '事件',
              dataIndex: 'event',
              key: 'event',
              width: 420,
              render: (text, record, index) => this.renderColumns(text, record, 'event', this.state.watchListChooseIndex),
            },
            {
              title: '金额',
              dataIndex: 'money',
              key: 'money',
              width: 180,
              render: (text, record, index) => this.renderColumns(text, record, 'money', this.state.watchListChooseIndex),
            },
            {
              title: '操作',
              key: 'action',
              fixed: 'right',
              width: 120,
              render: (text, record, index) => {
                const { editable } = record;
                return (
                  <div className="editable-row-operations">
                    {
                      editable ?
                        <span>
                          <a onClick={() => this.save(record.key)} href="#">保存</a>
                          <Popconfirm title="确认删除？" onConfirm={() => this.cancel(record.key)} okText="是" cancelText="否">
                            <a href="#">删除</a>
                          </Popconfirm>
                        </span>
                        : <a onClick={() => this.edit(record.key)} href="#">编辑</a>
                    }
                  </div>
                );
              },
            }],
            dataSource: [],
          }
        }
      ],
      watchListChooseIndex: 0,
      PopupVisible: false,
      guinow: 0,
      listenKey: 'm',
      listenVisible: false
    }
  }
  addNow() {
    this.setState({
      guinow: this.state.guinow + 1
    })
  }
  setWorkShow(e) {
    if (e !== "" && e !== "action") {
      this.setState({
        workShow: e
      })
    }
  }
  changeWatchList(e, key) {
    /*
    *选择leftApp中表单事件
    */
    if (e) {
      this.setState({
        watchListChooseIndex: key
      })

    }
  }
  addNewRow() {
    /*
    *添加新行
    */
    let data = JSON.stringify(this.MODEL[this.state.watchList[this.state.watchListChooseIndex].modelIndex].modelData.data)
    data = JSON.parse(data)
    let newKey = "" + (this.state.dataSource.length + 1)
    data.key = newKey;
    data.editable = true;
    //console.log('data', data)
    let newData = [...this.state.dataSource]
    newData.push(data)
    console.log('newData', newData)
    this.setState({
      dataSource: newData
    })

  }
  addNewWatchItem(e, data) {
    /*
    *添加新表
    */
    if (e === "") {
      message.error("表名不能为空值")
      return;
    }
    let arr = [...this.MODEL]
    data = arr[data]
    console.log('model', data)
    let params = {
      name: e
    }
    let items = {}
    items.columns = data.modelData.columns
    items.dataSource = []
    params.id = "" + (this.state.watchList.length)
    params.modelIndex = data.modelData.modelIndex;
    params.data = items;
    let allData = [...this.state.watchList];
    console.log('params', params)
    allData.push(params);
    this.setState({
      watchList: allData
    }, () => {
      message.success("新建成功！")
      this.setState({
        watchListChooseIndex: this.state.watchList.length - 1
      }, () => {
        this.showPopUp('', false);
      })
    })
  }
  delWatchItem(e, key) {
    /*
    *删除某表
    */
    e.stopPropagation()
    console.log('key', key)
    this.setState({
      watchListChooseIndex: key - 1
    }, () => {
      let newData = [...this.state.watchList]
      newData.splice(key, 1)
      this.setState({
        watchList: newData
      })
      message.success('删除成功！');
    })
  }
  /*
  *表内数据操作
  */
  renderColumns(text, record, column, index) {
    /*
    *返回可编辑的单元格
    */
    return (
      <EditableCell
        editable={record.editable}
        key={column + record.key}
        value={text}
        ID={column}
        onChange={value => this.handleChange(value, record.key, column)}
        setWorkShow={(e) => this.setWorkShow(e)}
      />
    );
  }
  handleChange(value, key, column) {
    /*
    *单元格内容改变
    */
    const newData = [...this.state.dataSource];
    const target = newData.filter(item => key === item.key)[0];
    // if (column==="money") {
    //   if (parseInt(value)) {
    //     alert('请注意输入的数值')
    //     return;
    //   }
    // }
    if (target) {
      target[column] = value;
      this.setState({
        dataSource: newData
      })
    }
  }
  edit(key) {
    /*
    *开启单行编辑
    */
    const newData = [...this.state.dataSource];
    const target = newData.filter(item => key === item.key)[0];
    if (target) {
      target.editable = true;
      this.setState({
        dataSource: newData
      })
    }
  }
  save(key) {
    /*
    *保存行数据
    */
    const newData = [...this.state.dataSource];
    const target = newData.filter(item => key === item.key)[0];
    if (target) {
      delete target.editable;
      this.setState({
        dataSource: newData
      })
      this.cacheData = newData.map(item => ({ ...item }));
    }
  }
  cancel(key) {
    /*
    *删除某行数据，并将它放入缓冲区
    */
    let newData = this.state.dataSource.filter((item) => {
      return item.key !== key
    })
    this.setState({
      dataSource: newData
    })
  }
  searchOnBlur(e) {
    let { value } = e.target;
    if (!this.state.tempDataSource) {
      this.state.tempDataSource = [...this.state.dataSource];
    }
    console.log('newData', this.state.tempDataSource)
    let newData = this.state.tempDataSource.filter(item => {
      console.log('item', item)
      for (const key in item) {
        if (Object.hasOwnProperty.call(item, key)) {
          if (item[key].indexOf(value) >= 0 && key !== 'key') {
            return item;
          }
        }
      }
    })
    this.setState({
      dataSource: newData
    })
  }
  openCloseListen(e) {
    this.setState({
      listenVisible: e
    })
  }
  /*
  *展示新建表页面
  */
  showPopUp(e, boo) {
    this.setState({
      PopupVisible: boo
    })
  }
  delLotsOfRow(e){
    if (this.state.__tempChooseRow__) {
      //arr.filter((x) => !to_remove.some((item) => arr.indexOf(x) === item));
      let newData=this.state.dataSource.filter((bitem)=> {
        let idList= this.state.__tempChooseRow__.map(v => v.key)
        return !idList.includes(bitem.key);
      });
      for (let i = 0; i < newData.length; i++) {
        newData[i].key=""+(i+1);
      }
      console.log('newData',newData )
      this.setState({
        dataSource:newData
      })
    }
  }
  render() {
    return (
      <div className="App" onKeyDown={(e) => this.handleKeyDown(e)}>
        <Listen listenKey={this.state.listenKey} listenVisible={this.state.listenVisible} openCloseListen={this.openCloseListen.bind(this)}></Listen>
        <ContextMenu showPopUp={this.showPopUp.bind(this)} addNewRow={this.addNewRow.bind(this)} openCloseListen={this.openCloseListen.bind(this)} />
        <Popup visible={this.state.PopupVisible} Close={this.showPopUp.bind(this)}
          MODEL={this.MODEL} addNewWatchItem={this.addNewWatchItem.bind(this)} className={this.state.PopupVisible ? 'blur' : ''}
        >
        </Popup>
        <AppHead PopupVisible={this.state.PopupVisible}></AppHead>
        <div className={this.state.PopupVisible ? 'flexRow blur' : 'flexRow'} style={{ width: '100vw', height: '85vh', overflow: 'hidden' }}>
          <WatchList data={this.state.watchList} chooseItem={this.state.watchListChooseIndex} changeChoose={this.changeWatchList.bind(this)}
            showPopUp={this.showPopUp.bind(this)} delWatchItem={this.delWatchItem.bind(this)}></WatchList>
          <WorkSpace addNewRow={this.addNewRow.bind(this)} searchOnBlur={this.searchOnBlur.bind(this)} delLotsOfRow={this.delLotsOfRow.bind(this)}
            columns={this.state.columns} dataSource={this.state.dataSource} rowSelection={this.state.rowSelection} workShow={this.state.workShow}></WorkSpace>
        </div>
      </div>
    );
  }
}

export default App;